package org.springblade.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 
 * @author zollty
 * @since 2022年5月26日
 */
@Configuration(proxyBeanMethods = false)
public class CustomCorsConfiguration implements WebMvcConfigurer {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${hilo.allowed-origins:#{null}}")
    private String[] uiOrigins;

    @Override
    public void addCorsMappings(final CorsRegistry registry) {
        this.allowedCors(registry.addMapping("/api/**"));
    }

    private void allowedCors(final CorsRegistration corsRegistration) {
        corsRegistration.allowedOrigins(new String[] { "*" }).allowedHeaders(new String[] { "*" })
                .allowedMethods(new String[] { "*" }).maxAge(3600L).allowCredentials(true);
    }

    /**
     * CORS——前后端分离项目，允许前端跨域请求
     */
    @Bean
    public FilterRegistrationBean<MyCorsFilter> corsFilterRegistration() {
        logger.info("init App_CorsFilter ---------------------------------------- ");
        CorsConfiguration config = new CorsConfiguration();
        if (uiOrigins != null) {
            for (String val : uiOrigins) {
                config.addAllowedOrigin(val);
            }
        }
        config.addAllowedOrigin("*");
        // DefaultValues：
        // 默认AllowedMethods 允许(GET HEAD POST)
        // ，AllowCredentials(true) 允许发送和处理Cookie
        // ，AllowedHeader(ALL) 允许所有Header
        config.applyPermitDefaultValues();
        config.addAllowedMethod(HttpMethod.OPTIONS);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 拦截的URL
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<MyCorsFilter> bean = new FilterRegistrationBean<MyCorsFilter>(
                new MyCorsFilter(source));
        bean.setName("App_CorsFilter");
        bean.setOrder(Ordered.LOWEST_PRECEDENCE);
        return bean;
    }

}